//
//  AppDelegate.m
//  Seizure
//
//  Created by student on 2/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"

#import "SetupViewController.h"
#import "SplashScreenViewController.h"
#import "DataManager.h"
#import "PatientTabViewController.h"
#import "MotionDetectionViewController.h"
#import "AlertedMapViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize navigationController = _navigationController;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

// for registering remote notifications
BOOL loginRequest = NO;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    // Override point for customization after application launch.
    self.navigationController = [[UINavigationController alloc] init];
    
    SplashScreenViewController *splashScreen = [[SplashScreenViewController alloc] initWithNibName:@"SplashScreenViewController" bundle:nil];
    [self.navigationController pushViewController:splashScreen animated:YES];
    
    [self.window addSubview:self.navigationController.view];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    [MotionDetectionViewController defaultUserBrightness];
}

// continue user registration after attempt at getting apple push key
- (void) continueSetupRegistration{
    for (id viewController in [self.navigationController viewControllers]){
        if ([viewController respondsToSelector:@selector(submitClicked)]){
            [viewController submitClicked];
        }
    }
}

// attempt to update the apns key for a logging in user
-(void)updateAPNSKey
{
    loginRequest = YES;
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}

// Application was able to register for push notifications  
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *apnsKey = [[[deviceToken description] stringByTrimmingCharactersInSet:
                          [NSCharacterSet characterSetWithCharactersInString:@"<>"]] 
                    stringByReplacingOccurrencesOfString:@" " withString:@""];
    
//    NSLog(@"My token is: %@", apnsKey);  // show APNS token
    
    // Set the apns key for a user
    DataManager *dm = [DataManager sharedInstance];
    if (loginRequest){
        // only have to upload the key
        [dm uploadAPNSKey:apnsKey];
        loginRequest = NO;
    }
    else {
        // user is registering
        [[dm user] setApnsKey:[apnsKey copy]];
        [self continueSetupRegistration];
    }
}

// Failed to get push notification key
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    // if it's not a login request, call was made by registration
    if (!loginRequest)
        [self continueSetupRegistration];
    else {
        // if it's a login request and failed, default back to NO
        loginRequest = NO;
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
    [MotionDetectionViewController defaultUserBrightness];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

#pragma mark Become Active
- (void)applicationDidBecomeActive:(UIApplication *)application
{    
    NSArray *viewControllers = [self.navigationController viewControllers];
    
    // we are going to look for MotionDetectionViewController in PatientTabViewController
    // because we want to update LocationHint text if location permissions
    for (id viewController in viewControllers){
        
        if ([viewController isKindOfClass:[PatientTabViewController class]]){
            
            // all Controllers inside PatientTabViewController
            NSArray *patientTabs = [(PatientTabViewController*)viewController viewControllers];
            for (id patientTab in patientTabs){ 
                
                if ([patientTab isKindOfClass:[MotionDetectionViewController class]]){
                    [(MotionDetectionViewController*)patientTab updateLocationHint];
                }
            }

        }
    }
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
       
    AlertedMapViewController *newController = [[AlertedMapViewController alloc] initWithNibName:@"AlertedMapViewController" bundle:nil dictonary:[userInfo copy]];
    [_navigationController pushViewController:newController animated:YES];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}



@end
